package com.example.backend.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.Executor;

/**
 * 性能优化配置
 * 解决工单创建超时问题
 */
@Configuration
@EnableAsync
@EnableTransactionManagement
public class PerformanceOptimizationConfig {

    /**
     * 异步任务执行器
     * 用于处理耗时的后台任务
     */
    @Bean(name = "taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);        // 核心线程数
        executor.setMaxPoolSize(20);        // 最大线程数
        executor.setQueueCapacity(100);     // 队列容量
        executor.setThreadNamePrefix("Async-Task-");
        executor.setKeepAliveSeconds(60);   // 空闲线程存活时间
        executor.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    /**
     * RestTemplate配置
     * 用于HTTP请求的超时设置
     */
    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        
        // 设置连接超时和读取超时
        restTemplate.getRequestFactory();
        
        return restTemplate;
    }
}
